const Koa = require("koa");
// const koaCORS = require("koa2-cors");
const Bodyparser = require("koa-bodyparser");
const Router = require("koa-router");

const url = "http://localhost";
const port = "3001";

const app = new Koa();
const router = new Router();

// app.use(
//   koaCORS({
//     origin: function (ctx) {
//       //设置允许来自指定域名请求
//       // if (ctx.url === '/test') {
//       return "*"; // 允许来自所有域名请求
//       // }
//       // return 'http://localhost:3000'; //只允许http://localhost:8080这个域名的请求
//     },
//     maxAge: 5, //指定本次预检请求的有效期，单位为秒。
//     credentials: true, //是否允许发送Cookie
//     allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], //设置所允许的HTTP请求方法
//     allowHeaders: ["Content-Type", "Authorization", "Accept"], //设置服务器支持的所有头信息字段
//     exposeHeaders: ["WWW-Authenticate", "Server-Authorization"],
//   })
// );

app.use(Bodyparser());

// 处理 options 预检请求
router.all("/data", (ctx, next) => {
  ctx.set({
    "Access-Control-Allow-Origin": "*", // "http://localhost:3000",
    "Access-Control-Allow-Methods": "GET, POST, PUT",
    "Access-Control-Allow-Headers":
      "Origin,X-Requested-With,Content-Type,Accept",
  });
  if (ctx.request.method === "OPTIONS") {
    console.log("in options");
    console.log(ctx.request);

    ctx.status = 204;
  } else if (ctx.request.method === "POST") {
    console.log("in post", ctx.request);
    ctx.body = "body 6666";
    ctx.status = 200;
  }
});

// 路由
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(port, () => {
  console.log(`服务在 ${url}:${port} 上启动起来了`);
});
